package cn.codesea.housework_user.ui.worker;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.codesea.housework_user.R;
import cn.codesea.housework_user.adapter.listener.OnRecyclerItemClickServiceVOListener;
import cn.codesea.housework_user.adapter.WorkerSerListRcvAdapter;
import cn.codesea.housework_user.entity.Service;
import cn.codesea.housework_user.entity.ServiceVO;
import cn.codesea.housework_user.entity.Worker;
import cn.codesea.housework_user.net.ServiceGenerator;
import cn.codesea.housework_user.net.data.Result;
import cn.codesea.housework_user.net.service.SerService;
import cn.codesea.housework_user.net.service.WorkerService;
import cn.codesea.housework_user.utils.SPUtil;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 工作人员注册阶段，选择 所属服务
 */
public class ServiceListWorkerActivity extends AppCompatActivity {

    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.submit_tv)
    TextView submit_tv;

    WorkerSerListRcvAdapter adapter;
    List<ServiceVO> mDatas = new ArrayList<>();
    private LinearLayoutManager mLinearLayoutManager;

    Worker worker;

    String type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_servicelist_worker);
        ButterKnife.bind(this);
        init();
    }

    private void init(){
        initView();
        initData();
    }

    private void initData() {
        worker = (Worker) getIntent().getSerializableExtra("worker");

        SerService serService = ServiceGenerator.createService(SerService.class);
        Call<Result> call = serService.getService();
        call.enqueue(new Callback<Result>(){
            @Override
            public void onResponse(Call<Result> call, Response<Result> response) {
                Result result = response.body();
                Type type = new TypeToken<List<Service>>(){}.getType();
                List<Service> sers = new Gson().fromJson(String.valueOf(result.getRes()),type);

                List<ServiceVO> ms = new ArrayList<>();

                for (Service s : sers){
                    if (s.getPid() == 0){
                        ServiceVO sVO = new ServiceVO();
                        sVO.setId(s.getId());
                        sVO.setPid(s.getPid());
                        sVO.setName(s.getName());
                        sVO.setDesc(s.getDesc());
                        sVO.setMark(s.getMark());
                        List<Service> services = new ArrayList<>();
                        sVO.setServices(services);
                        ms.add(sVO);
                    }
                }

                for (Service s : sers){
                    if (s.getPid() != 0){

                        for (ServiceVO sVO : ms){
                            if (s.getPid() == sVO.getId()){
                                sVO.getServices().add(s);
                                break;
                            }
                        }

                    }
                }

                mDatas.clear();
                mDatas.addAll(ms);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(Call<Result> call, Throwable t) {

            }
        });


        type = getIntent().getStringExtra("type");

    }

    private void initView(){
        // 初始化 toolbar
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        adapter = new WorkerSerListRcvAdapter(this,mDatas);
        adapter.setRecyclerItemClickListener(new OnRecyclerItemClickServiceVOListener() {
            @Override
            public void onItemClick(int Position, List<ServiceVO> list) {

            }
        });
        mLinearLayoutManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
        mRecyclerView.setLayoutManager(mLinearLayoutManager);
        mRecyclerView.setAdapter(adapter);

    }

    @OnClick(R.id.submit_tv)
    public void submit_tv(){

        List<Service> services = new ArrayList<>();
        for (ServiceVO sVO : mDatas){
            for (Service service : sVO.getServices()){
                if (service.isChecked()){
                    services.add(service);
                }
            }
        }
        worker.setServices(services);

        WorkerService service = ServiceGenerator.createService(WorkerService.class);

        if ("update".equals(type)){
            // 修改流程
            Call<Result> call = service.workerUpdate(worker);
            call.enqueue(new Callback<Result>(){
                @Override
                public void onResponse(Call<Result> call, Response<Result> response) {
                    resultProcess(response.body(),"更新");
                }

                @Override
                public void onFailure(Call<Result> call, Throwable t) {
                    Toast.makeText(ServiceListWorkerActivity.this,"网络错误!",Toast.LENGTH_SHORT).show();
                }
            });

        }else {
            // 注册流程
            Call<Result> call = service.workerRegister(worker);
            call.enqueue(new Callback<Result>(){
                @Override
                public void onResponse(Call<Result> call, Response<Result> response) {
                    resultProcess(response.body(),"注册");
                }

                @Override
                public void onFailure(Call<Result> call, Throwable t) {
                    Toast.makeText(ServiceListWorkerActivity.this,"网络错误!",Toast.LENGTH_SHORT).show();
                }
            });

        }
    }

    /**
     * 结果处理
     */
    public void resultProcess(Result result,String msg){
        if (result.getState() == 200){
            Dialog dialog = new AlertDialog.Builder(ServiceListWorkerActivity.this)
                    .setTitle("提示")
                    .setMessage(msg + "成功！")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            SPUtil.logout(ServiceListWorkerActivity.this);// 登出
                            startActivity(new Intent(ServiceListWorkerActivity.this,LoginWorkerActivity.class));
                            finish();
                        }
                    })
                    .create();
            dialog.setCancelable(false);
            dialog.show();
        }else {
            Dialog dialog = new AlertDialog.Builder(ServiceListWorkerActivity.this)
                    .setTitle("提示")
                    .setMessage(msg + "失败！")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    })
                    .create();
            dialog.setCancelable(false);
            dialog.show();
        }
    }

}
